package cn.ruanyun.backInterface.modules.fadada.serviceimpl;

import cn.ruanyun.backInterface.common.constant.CommonConstant;
import cn.ruanyun.backInterface.common.enums.BooleanTypeEnum;
import cn.ruanyun.backInterface.common.utils.*;
import cn.ruanyun.backInterface.common.vo.Result;
import cn.ruanyun.backInterface.modules.base.pojo.User;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IUserService;
import cn.ruanyun.backInterface.modules.fadada.dto.PushTwoElectronicContractDto;
import cn.ruanyun.backInterface.modules.fadada.mapper.MyContractSigningMapper;
import cn.ruanyun.backInterface.modules.fadada.pojo.MyContractSigning;
import cn.ruanyun.backInterface.modules.fadada.pojo.MyContractSigningCheck;
import cn.ruanyun.backInterface.modules.fadada.service.IMyContractSigningCheckService;
import cn.ruanyun.backInterface.modules.fadada.service.IMyContractSigningService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fadada.sdk.client.FddClientBase;
import com.fadada.sdk.client.request.ExtsignReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;


/**
 * 我的合同签署接口实现
 * @author z
 */
@Slf4j
@Service
@Transactional
public class IMyContractSigningServiceImpl extends ServiceImpl<MyContractSigningMapper, MyContractSigning> implements IMyContractSigningService {

    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMyContractSigningCheckService myContractSigningService;


    @Override
    public Result<MyContractSigning> getMyContractSigning() {

        return Optional.ofNullable(this.getOne(Wrappers.<MyContractSigning>lambdaQuery()
        .eq(MyContractSigning::getCreateBy, securityUtil.getCurrUser().getId())
        .orderByDesc(MyContractSigning::getCreateTime)
        .last("limit 1")))
        .map(myContractSigning -> new ResultUtil<MyContractSigning>().setData(myContractSigning, "获取我的合同成功！"))
        .orElse(new ResultUtil<MyContractSigning>().setErrorMsg(202, "暂无数据！"));
    }

    @Override
    public Result<Object> signContract(PushTwoElectronicContractDto pushTwoElectronicContractDto) {


     return  Optional.ofNullable(this.getOne(Wrappers.<MyContractSigning>lambdaQuery()
               .eq(MyContractSigning::getCreateBy, securityUtil.getCurrUser().getId())
               .last("limit 1"))).map(myContractSigning -> {

           FddClientBase base = new FddClientBase(CommonConstant.F_APP_ID,CommonConstant.F_APP_SECRET,CommonConstant.F_VERSION,CommonConstant.F_HOST);

           //填充乙方信息
           ToolUtil.copyProperties(pushTwoElectronicContractDto, myContractSigning);

           //字体大小
           String fontSize = "";

           //字体类型
           String fontType = "";

           String contractId = CommonUtil.getRandomNum();

           //填充内容
           String paramter = getparamter(myContractSigning);

           String result = base.invokeGenerateContract(myContractSigning.getTemplateId(), contractId, pushTwoElectronicContractDto.getDocTitle(),
                   null, null, paramter, null);

           if ("1000".equals(JSONObject.parseObject(result).getString("code"))) {

               myContractSigning.setDownloadUrl(JSONObject.parseObject(result).getString("download_url"))
                       .setContractId(contractId)
                       .setViewPdfUrl(JSONObject.parseObject(result).getString("viewpdf_url"))
                       .setFillSuccess(BooleanTypeEnum.YES);

               this.updateById(myContractSigning);

               MyContractSigningCheck myContractSigningCheck = new MyContractSigningCheck();
               myContractSigningCheck.setContractId(contractId);
               myContractSigningCheck.setCreateBy(myContractSigning.getCreateBy());
               myContractSigningService.save(myContractSigningCheck);


               return new ResultUtil<>().setSuccessMsg("填充合同成功！");
           }else {

               return new ResultUtil<>().setErrorMsg(JSONObject.parseObject(result).getIntValue("code"),
                       JSONObject.parseObject(result).getString("msg"));
           }
       }).orElse(new ResultUtil<>().setErrorMsg(203, "暂无合同"));
    }

    @Override
    public Result<Object> partyTwoExtSign() {

        return Optional.ofNullable(this.getOne(Wrappers.<MyContractSigning>lambdaQuery()
        .eq(MyContractSigning::getCreateBy, securityUtil.getCurrUser().getId())
        .last("limit 1"))).map(myContractSigning -> {

            User user = userService.getById(securityUtil.getCurrUser().getId());

            String transactionId = CommonUtil.getRandomNum();
            //手动签署合同
            FddClientBase base = new FddClientBase(CommonConstant.F_APP_ID,CommonConstant.F_APP_SECRET,CommonConstant.F_VERSION,CommonConstant.F_HOST);
            ExtsignReq req = new ExtsignReq();
            req.setCustomer_id(user.getCustomerId());
            req.setTransaction_id(transactionId);
            req.setContract_id(myContractSigning.getContractId());
            req.setDoc_title(myContractSigning.getPartyName() + "合同");
            req.setNotify_url("http://121.196.28.116:8083/ruanyun/myContractSigningCheck/fadadaPartyTwoNotify");
            String signUrl = base.invokeExtSign(req);
            return new ResultUtil<>().setData(signUrl, "获取合同签署地址成功！");

        }).orElse(new ResultUtil<>().setErrorMsg(202, "当前暂无数据！"));
    }

    @Override
    public Result<Object> partyOneExtSign(String id) {

        return Optional.ofNullable(myContractSigningService.getById(id)).map(myContractSigning -> {


            User user = userService.getById(securityUtil.getCurrUser().getId());

            String transactionId = CommonUtil.getRandomNum();
            //手动签署合同
            FddClientBase base = new FddClientBase(CommonConstant.F_APP_ID,CommonConstant.F_APP_SECRET,CommonConstant.F_VERSION,CommonConstant.F_HOST);
            ExtsignReq req = new ExtsignReq();
            req.setCustomer_id(user.getCustomerId());
            req.setTransaction_id(transactionId);
            req.setContract_id(myContractSigning.getContractId());
            req.setDoc_title("合同");
            req.setNotify_url("http://121.196.28.116:8083/ruanyun/myContractSigningCheck/fadadaOneNotify");
            String signUrl = base.invokeExtSign(req);
            return new ResultUtil<>().setData(signUrl, "获取合同签署地址成功！");
        }).orElse(new ResultUtil<>().setErrorMsg(202, "当前暂无数据！"));
    }




    private String getparamter(MyContractSigning myContractSigning) {

        JSONObject paramter = new JSONObject();

        /*------------------ 甲方填充信息---------------------*/
        myContractSigning.setContractNumber(myContractSigning.getBeginYear() + myContractSigning
                .getBeginMonth() + myContractSigning.getBeginDay() + CommonUtil.getRandomNum());
        paramter.put("contractNumber", myContractSigning.getContractNumber());
        paramter.put("beginYear", myContractSigning.getBeginYear());
        paramter.put("beginMonth", myContractSigning.getBeginMonth());
        paramter.put("beginDay", myContractSigning.getBeginDay());
        paramter.put("endYear", myContractSigning.getEndYear());
        paramter.put("endMonth", myContractSigning.getEndMonth());
        paramter.put("endDay", myContractSigning.getEndDay());
        paramter.put("totalMoney", myContractSigning.getTotalMoney());
        paramter.put("userBuyMoney", myContractSigning.getUserBuyMoney());
        paramter.put("depositMoney", myContractSigning.getDepositMoney());
        paramter.put("couponMoney", myContractSigning.getCouponMoney());


        /*-------------------乙方填充信息--------------------*/
        paramter.put("partyName",myContractSigning.getPartyName());
        paramter.put("partyUserName", myContractSigning.getPartyUserName());
        paramter.put("partyBankName", myContractSigning.getPartyBankName());
        paramter.put("partyBankCode", myContractSigning.getPartyBankCode());
        paramter.put("partyAliPay", myContractSigning.getPartyAliPay());
        paramter.put("partyEmail", myContractSigning.getPartyEmail());
        paramter.put("partyPhone", myContractSigning.getPartyPhone());
        paramter.put("partyAddress", myContractSigning.getPartyAddress());

        return paramter.toString();
    }


}